<?php
/**
 * 自增ID
 * User: dxk
 * Date: 2020/07/17
 */

namespace App\Library\Service;

use App\Service\EasyRedis;

class IncService
{
    private static $support_key = [
        'payment',//交易记录
        'service_order',//服务订单
        'company_order_pay',//服务订单
        'company_order_code',//服务订单激活码
    ];

    /**
     * 获取自增ID
     * @param $table
     * @param int $num
     * @return int
     */
    public static function getDayAutoIncID($table, int $num = 1): int
    {
        $table = trim($table);
        if (empty($table)) {
            throw new \Exception('获取自增ID服务不可用2');
        }
        if (!in_array($table, self::$support_key)) {
            throw new \Exception('获取自增ID服务不可用3');
        }
        $date = date('Ymd');
        $inc_key = 'table_inc_' . ':' . $date . ':' . $table;
        $PRedis = EasyRedis::getRedis($table);
        if ($num <= 1) {
            $inc_id = $PRedis->incr($inc_key);
        } else {
            $inc_id = $PRedis->incrBy($inc_key, $num);
        }
        $PRedis->expire($inc_key, 3600 * 24 * 2);
        if (!is_numeric($inc_id) || $inc_id <= 0) {
            throw new \Exception('获取自增ID服务不可用4');
        }
        return $inc_id;
    }
}
